package com.example.dllo.keepdemo.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/1/18.
 */
public class DiskCache implements ImageLoader.ImageCache {
    private String cacheDir = "";

    public DiskCache() {
        //判断外置SD卡是否处于挂载的状态
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //获取根路径
            File root = Environment.getExternalStorageDirectory();
            File cacheFile = new File(root.getAbsolutePath() + "/cacheKeep");
            //如果该文件夹不存在，创建
            if (!cacheFile.exists()) {
                cacheFile.mkdir();
            }
            cacheDir = cacheFile.getAbsolutePath(); //缓存路径
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        //路径下的文件名
        return BitmapFactory.decodeFile(cacheDir + "/" + url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(cacheDir + "/" + url);
            String path = cacheDir + "/" + url;
            Log.d("DiskCache", path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
